<template>
  <div>
    <n-grid :x-gap="12" :y-gap="8" :cols="4">
      <n-gi :span="1">
        <n-space style="margin-bottom: 10px">
          <n-button type="primary" @click="editTask({ id: '' })"> 新增 </n-button>
          <n-button
            ghost
            :type="checkedRowKeysRef.length === 0 ? undefined : 'warning'"
            :disabled="checkedRowKeysRef.length === 0"
            @click="deleteTask()"
          >
            批量删除
          </n-button>
        </n-space>
      </n-gi>
      <n-gi :span="3">
        <n-space justify="end">
          <n-input v-model:value="queryParams.taskName" placeholder="请输入任务名称" />
          <n-input v-model:value="queryParams.taskTo" placeholder="请输入接收者" />
          <n-button type="primary" @click="getTaskList"> 查询 </n-button>
          <n-button @click="reset"> 重置 </n-button>
        </n-space>
      </n-gi>
    </n-grid>
    <n-data-table
      :loading="spinning"
      :columns="columns"
      :data="tableData.list"
      :pagination="pagination"
      :remote="true"
      :row-key="(row: Record<string, any>) => row.id"
      :bordered="false"
      size="small"
      :style="{ height: contentHeight }"
      flex-height
      @update:checked-row-keys="handleCheck"
      @update:page="pageChange"
    />
    <form-modal ref="formModal" v-model:showModal="showEditorModal" :editor-data="model" @refresh="getTaskList" />
    <detail-modal ref="detailModal" v-model:showModal="showDetailModal" :detail-date="model" />
  </div>
</template>

<script lang="ts">
  import { h, defineComponent, ref, reactive, computed, getCurrentInstance } from 'vue'
  import { useMessage, useDialog } from 'naive-ui'
  import { udpAppStore } from 'udp/store/app-store'
  import formModal from './formModal.vue'
  import detailModal from './detailModal.vue'
  import { Row } from './type'

  interface Operate {
    name: string
    isDelete?: boolean
    method(row: Row): void
  }
  const createColumns = (options: Operate[]) => {
    return [
      {
        type: 'selection'
      },
      {
        title: '任务名称',
        key: 'taskName',
        ellipsis: true
      },
      {
        title: '路径',
        key: 'taskUrl',
        ellipsis: true
      },
      {
        title: '参数',
        key: 'taskParam'
      },
      {
        title: '接收者',
        key: 'taskTo'
      },
      {
        title: 'cron表达式',
        key: 'taskCron'
      },
      {
        title: '任务描述',
        key: 'taskDesc',
        ellipsis: true
      },
      {
        title: '操作',
        key: 'options',
        render(row: Row) {
          const spans = options.map(v => {
            return h(
              'span',
              {
                style: {
                  color: v.isDelete ? '#c43b3b' : '#0080EB',
                  marginRight: '15px',
                  cursor: 'pointer'
                },
                onClick: () => v.method(row)
              },
              { default: () => v.name }
            )
          })
          return spans
        }
      }
    ]
  }

  export default defineComponent({
    name: 'Home',
    components: { formModal, detailModal },
    setup() {
      const internalInstance = getCurrentInstance()
      const $api = internalInstance?.appContext.config.globalProperties.$api
      // 弹框相关
      const dialog = useDialog()
      const message = useMessage()
      const formModal = ref()
      const detailModal = ref()
      const showDetailModal = ref(false)
      const showEditorModal = ref(false)
      const model = ref({ id: '' })

      // table相关
      const tableData = reactive({
        list: []
      })
      const spinning = ref(false)
      const pagination = reactive({
        pageSize: 10,
        itemCount: 0,
        page: 1
      })
      const checkedRowKeysRef = ref([])
      const handleCheck = (rowKeys: never[]) => {
        checkedRowKeysRef.value = rowKeys
      }
      // table高度
      const appStore = udpAppStore()
      const contentHeight = computed(() => appStore.contentHeight.replace(')', ' - 90px )'))

      // 查询相关
      const queryParams = reactive({
        taskName: '',
        taskTo: ''
      })
      // 请求数据
      const queryTableData = () => {
        spinning.value = true
        $api
          .get('/sys/task/findbycondition/page', {
            page: pagination.page - 1,
            size: pagination.pageSize,
            ...queryParams
          })
          .then((res: any) => {
            tableData.list = res.content || []
            pagination.itemCount = res.totalElements
          })
          .finally(() => {
            spinning.value = false
          })
      }
      // 获取数据
      const getTaskList = () => {
        pagination.page = 1
        queryTableData()
      }
      // 切换分页
      const pageChange = (page: number) => {
        pagination.page = page
        queryTableData()
      }
      // 重置
      const reset = () => {
        queryParams.taskName = ''
        queryParams.taskTo = ''
        getTaskList()
      }
      // 编辑
      const editTask = (row: Row) => {
        model.value = row
        showEditorModal.value = true
      }
      // 删除相关
      const deleteTask = (id?: string) => {
        const key = id || checkedRowKeysRef.value.join(',')
        dialog.warning({
          title: '删除',
          content: '确定删除该任务吗？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            $api.delete(`/sys/task/deletes/${key}`).then((res: any) => {
              if (res) {
                message.success('删除成功')
                getTaskList()
              } else {
                message.error('删除失败')
              }
            })
          }
        })
      }

      // 操作
      const options: Operate[] = [
        {
          name: '详情',
          method(row: Row) {
            model.value = row
            showDetailModal.value = true
          }
        },
        {
          name: '编辑',
          method: (row: Row) => editTask(row)
        },
        {
          name: '删除',
          isDelete: true,
          method: (row: Row) => deleteTask(row.id)
        }
      ]

      getTaskList()

      return {
        queryParams,
        tableData,
        contentHeight,
        spinning,
        columns: createColumns(options),
        checkedRowKeysRef,
        pagination,
        handleCheck,
        pageChange,
        getTaskList,
        reset,
        editTask,
        deleteTask,
        formModal,
        detailModal,
        model,
        showDetailModal,
        showEditorModal
      }
    }
  })
</script>
<style lang="less" scoped></style>
